﻿using System.Net;
using SnmpSharpNet;

namespace snmpTest
{
    public class Snmp
    {
        public static string GetSnmp(string oid, string host, int port = 161)
        {
            string get = "";

            //共同体类型
            OctetString community = new OctetString("public");
            AgentParameters param = new AgentParameters(community);

            //设置snmp版本             
            param.Version = (int)SnmpVersion.Ver1;
            IpAddress agent = new IpAddress(host);

            //构建目标            
            UdpTarget target = new UdpTarget((IPAddress)agent, port, 2000, 1);

            Pdu pdu = new Pdu(PduType.Get);
            pdu.VbList.Add(oid);

            //发送snmp请求
            SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

            get = result.Pdu.VbList[0].Value.ToString();

            return get;
        }

        public static void SetSnmp(string oid, string host, int port = 161, string value = "")
        {
            //共同体类型
            OctetString community = new OctetString("private");
            AgentParameters param = new AgentParameters(community);

            //设置snmp版本
            param.Version = (int)SnmpVersion.Ver1;
            IpAddress agent = new IpAddress(host);

            //构建目标            
            UdpTarget target = new UdpTarget((IPAddress)agent, port, 2000, 1);

            Pdu pdu = new Pdu(PduType.Set);
            pdu.VbList.Add(new SnmpSharpNet.Oid(oid), new OctetString(value));

            //发送snmp请求
            SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
        }
    }
}